package com.platform.service.impl;

import com.platform.dao.*;
import com.platform.entity.*;
import com.platform.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.platform.service.AgentGoodsService;

/**
 * Service实现类
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2018-10-07 20:42:59
 */
@Service("agentGoodsService")
public class AgentGoodsServiceImpl implements AgentGoodsService {
    @Autowired
    private AgentGoodsDao agentGoodsDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private GoodsCategoryDao goodsCategoryDao;
    @Autowired
    private GoodsGalleryDao goodsGalleryDao;
    @Autowired
    private GoodsSpecificationDao goodsSpecificationDao;
    @Autowired
    private ProductDao productDao;

    @Override
    public AgentGoodsEntity queryObject(Integer id) {
        return agentGoodsDao.queryObject(id);
    }

    @Override
    public List<AgentGoodsEntity> queryList(Map<String, Object> map) {
        return agentGoodsDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return agentGoodsDao.queryTotal(map);
    }

    @Override
    public int save(AgentGoodsEntity agentGoods) {
        return agentGoodsDao.save(agentGoods);
    }

    @Override
    public int update(AgentGoodsEntity agentGoods) {
        return agentGoodsDao.update(agentGoods);
    }

    @Override
    public int delete(Integer id) {
        return agentGoodsDao.delete(id);
    }

    @Override
    public int deleteBatch(Integer[] ids) {
        return agentGoodsDao.deleteBatch(ids);
    }

    @Override
    public AgentGoodsEntity addGoodsToMyShop(AgentEntity agent, String agentGoodsIds, Long applyUserId){
        //保存代理记录单
        AgentGoodsEntity entity = new AgentGoodsEntity();
        entity.setAgentId(agent.getId());
        entity.setAgentGoodsIds(agentGoodsIds);
        entity.setApplyUserId(applyUserId);
        entity.setApplyTime(new Date());
        entity.setIsCert(1);
        agentGoodsDao.save(entity);

        //开始拷贝商品信息及关联信息
        if(agentGoodsIds != null && agentGoodsIds.trim().length() > 0){
            String[] ids = agentGoodsIds.split("_");
            if(ids != null && ids.length > 0){
                for(String id : ids){
                    //判断是否已经代理
                    GoodsEntity goodsEntity = goodsDao.queryObject(id);
                    String goodsSn = goodsEntity.getGoodsSn();
                    Map param = new HashMap();
                    param.put("agentGoodsId", id);
                    param.put("rootDeptId", agent.getAgentRootDeptId());
                    List<GoodsEntity> goodsEntities = goodsDao.queryByAgentGoodsId(param);
                    if (goodsEntities.size() != 0)
                        continue;

                    //保存商品基本信息
                    GoodsEntity sourceGoods = goodsDao.queryObject(id);
                    GoodsEntity targetGoods = new GoodsEntity();
                    copyGoods(sourceGoods, targetGoods);
                    targetGoods.setRootDeptId(agent.getAgentRootDeptId());
                    targetGoods.setAgentGoodsId(sourceGoods.getId());
                    targetGoods.setCreateUserDeptId(agent.getAgentRootDeptId());
                    targetGoods.setCreateUserId(applyUserId);
                    targetGoods.setIsAllowAgent(0); //默认不能再被代理
                    goodsDao.save(targetGoods);

                    //保存商品与分类关联
                    List<GoodsCategoryEntity> gcList = goodsCategoryDao.queryList(sourceGoods.getId());
                    if(gcList != null && gcList.size() > 0){
                        for (GoodsCategoryEntity gcSource : gcList){
                            GoodsCategoryEntity gcTarget = new GoodsCategoryEntity();
                            gcTarget.setGoodId(targetGoods.getId());
                            gcTarget.setCategoryId(gcSource.getCategoryId());
                            goodsCategoryDao.save(gcTarget);
                        }
                    }

                    //保存商品轮播图
                    List<GoodsGalleryEntity> ggList = goodsGalleryDao.queryListByGoodsId(sourceGoods.getId());
                    if(ggList != null && ggList.size() > 0){
                        for (GoodsGalleryEntity ggSource : ggList){
                            GoodsGalleryEntity ggTarget = new GoodsGalleryEntity();
                            copyGoodsGallery(ggSource, ggTarget);
                            ggTarget.setGoodsId(targetGoods.getId());
                            goodsGalleryDao.save(ggTarget);
                        }
                    }

                    //保存商品规格设置
                    List<GoodsSpecificationEntity> gsList = goodsSpecificationDao.queryListByGoodsId(sourceGoods.getId());
                    Map<Integer, Integer> mapping = new HashMap<Integer, Integer>();    //存储规格新旧ID之间的映射关系，后面做替换用的
                    if(gsList != null && gsList.size() > 0){
                        for (GoodsSpecificationEntity gsSource : gsList){
                            GoodsSpecificationEntity gsTarget = new GoodsSpecificationEntity();
                            copyGoodsSpecification(gsSource, gsTarget);
                            gsTarget.setGoodsId(targetGoods.getId());
                            gsTarget.setRootDeptId(agent.getAgentRootDeptId());
                            goodsSpecificationDao.save(gsTarget);

                            mapping.put(gsSource.getId(), gsTarget.getId());
                        }
                    }

                    //保存商品库存信息
                    List<ProductEntity> productList = productDao.queryListByGoodsId(sourceGoods.getId());
                    if(productList != null && productList.size() > 0){
                        for (ProductEntity productSource : productList){
                            ProductEntity productTarget = new ProductEntity();
                            productTarget.setGoodsId(targetGoods.getId());
                            productTarget.setGoodsSn(productSource.getGoodsSn());
                            productTarget.setGoodsNumber(10);
                            productTarget.setRetailPrice(productSource.getRetailPrice());
                            productTarget.setMarketPrice(productSource.getMarketPrice());
                            productTarget.setRootDeptId(agent.getAgentRootDeptId());

                            String specificationIds = calcGoodsSpecificationIds(productSource.getGoodsSpecificationIds(), mapping);
                            if (specificationIds == null)
                                specificationIds = "";
                            productTarget.setGoodsSpecificationIds(specificationIds);

                            productDao.save(productTarget);
                        }
                    }
                }
            }
        }

        return entity;
    }

    private String calcGoodsSpecificationIds(String sourceGoodsSpecificationIds, Map<Integer, Integer> mapping){
        if(sourceGoodsSpecificationIds != null && sourceGoodsSpecificationIds.trim().length() > 0){
            String[] ids = sourceGoodsSpecificationIds.split("_");
            if(ids != null && ids.length > 0){
                Integer[] result = new Integer[ids.length];
                for(int i=0; i<ids.length; i++){
                    result[i] = mapping.get(Integer.valueOf(ids[i]));
                }
                String resultStr = "";
                for(Integer index : result){
                    resultStr += index + "_";
                }
                return resultStr;
            }
        }
        return null;
    }

    private void copyGoodsSpecification(GoodsSpecificationEntity source, GoodsSpecificationEntity target){
        if(source != null && target != null){
            target.setSpecificationId(source.getSpecificationId());
            target.setValue(source.getValue());
            target.setPicUrl(source.getPicUrl());
        }
    }

    private void copyGoodsGallery(GoodsGalleryEntity source, GoodsGalleryEntity target){
        if(source != null && target != null){
            target.setImgUrl(source.getImgUrl());
            target.setImgDesc(source.getImgDesc());
            target.setSortOrder(source.getSortOrder());
        }
    }

    private void copyGoods(GoodsEntity source, GoodsEntity target){
        if(source != null && target != null){
            target.setIsOnSale(source.getIsOnSale());
            target.setIsDelete(source.getIsDelete());
            target.setAddTime(new Date());
            target.setPrimaryProductId(source.getPrimaryProductId());
            target.setAccessUserGrade(source.getAccessUserGrade());
            target.setAppExclusivePrice(source.getAppExclusivePrice());
            target.setAttributeCategory(source.getAttributeCategory());
            target.setClientPrice(source.getClientPrice());
            target.setCollageEndDate(source.getCollageEndDate());
            target.setCollageMemo(source.getCollageMemo());
            target.setCollageMiniNum(source.getCollageMiniNum());
            target.setExtraPrice(source.getExtraPrice());
            target.setCounterPrice(source.getCounterPrice());
            target.setFirstDiscount(source.getFirstDiscount());
            target.setFirstNum(source.getFirstNum());
            target.setFuturesListingDate(source.getFuturesListingDate());
            target.setFuturesMemo(source.getFuturesMemo());
            target.setClientPrice(source.getClientPrice());
            target.setGoodsBrief(source.getGoodsBrief());
            target.setGoodsDesc(source.getGoodsDesc());
            target.setGoodsSn(source.getGoodsSn());
            target.setGoodsUnit(source.getGoodsUnit());
            target.setIsAllowAgent(source.getIsAllowAgent());
            target.setIsAppExclusive(source.getIsAppExclusive());
            target.setIsHot(source.getIsHot());
            target.setIsLimited(source.getIsLimited());
            target.setIsNew(source.getIsNew());
            target.setKeywords(source.getKeywords());
            target.setListPicUrl(source.getListPicUrl());
            target.setMarketPrice(source.getMarketPrice());
            target.setName(source.getName());
            target.setPrimaryPicUrl(source.getPrimaryPicUrl());
            target.setPrimaryProductId(source.getPrimaryProductId());
            target.setPromotionDesc(source.getPromotionDesc());
            target.setPromotionTag(source.getPromotionTag());
            target.setRetailPrice(source.getRetailPrice());
            target.setSaleType(source.getSaleType());
            target.setSecondDiscount(source.getSecondDiscount());
            target.setSecondNum(source.getSecondNum());
            target.setSellVolume(source.getSellVolume());
            target.setSortOrder(source.getSortOrder());
            target.setUnitPrice(source.getUnitPrice());
            target.setVipClientPrice(source.getVipClientPrice());
            target.setPriceType(source.getPriceType());
        }
    }
}
